package com.jeeplus.modules.guide.utils;

import net.sf.json.JSONObject;
import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * http请求处理处理工具类
 *
 * @author azj
 * @date 2020-05-18/下午1:43:15
 */
public class HttpRequestUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("method", "post");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset:UTF-8");
            //conn.setRequestProperty("Content-type", "application/json; charset=utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
          /*  // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            */
            if (param != null)
                conn.getOutputStream().write(param.getBytes("utf-8"));
            // flush输出流的缓冲
            //out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error("url:" + url);
            logger.error("发送 sendPost 请求出现异常！" + e);
            e.printStackTrace();
            return null;
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String sendGet(String url,String appkey) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("method", "get");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset:UTF-8");
            //conn.setRequestProperty("Content-type", "application/json; charset=utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Authorization", appkey);
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error("url:" + url);
            logger.error("发送 sendPost 请求出现异常！" + e);
            e.printStackTrace();
            return null;
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }



    public static String sendPostByToken(String url, String token) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("method", "post");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset:UTF-8");
            //conn.setRequestProperty("Content-type", "application/json; charset=utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("token", token);
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error("url:" + url);
            logger.error("发送 sendPost 请求出现异常！" + e);
            e.printStackTrace();
            return null;
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String getSisutionThing(String url,String oid,String ids,String titleIds,String token){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(url+"?packageOid="+oid+"&titleOids="+titleIds+"&valOids="+ids)
                .method("GET", null)
                .addHeader("token", token)
                .addHeader("Cookie", "JSESSIONID=C371CF8BC044BA480E028EA03924A618; JSESSIONID_SHIRO=49ab1b01-caa5-456d-9666-9bd5e8e982f2C371CF8BC044BA480E028EA03924A618")
                .build();
        try{
            Response response = client.newCall(request).execute();
            return response.body().string().toString();
        }catch (Exception e){}
        return null;
    }
    public static String sendPostByTokenParam(String url,String jsonParam, String token) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("method", "post");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-type", "application/json");
            //conn.setRequestProperty("Content-type", "application/json; charset=utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("token", token);
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 转换为字节数组
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            if (jsonParam != null)
                conn.getOutputStream().write(jsonParam.getBytes("utf-8"));
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.error("url:" + url);
            logger.error("发送 sendPost 请求出现异常！" + e);
            e.printStackTrace();
            return null;
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


    public static String getJsonData(JSONObject jsonParam, String urls) {
        StringBuffer sb = new StringBuffer();
        try {
            // 创建url资源
            URL url = new URL(urls);
            // 建立http连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置允许输出
            conn.setDoOutput(true);
            // 设置允许输入
            conn.setDoInput(true);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setRequestMethod("POST");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            // 转换为字节数组
            byte[] data = (jsonParam.toString()).getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String
                    .valueOf(data.length));
            // 设置文件类型:
            conn.setRequestProperty("contentType", "application/json");
            // 开始连接请求
            conn.connect();
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // 写入请求的字符串
            out.write((jsonParam.toString()).getBytes("UTF-8"));
            out.flush();
            out.close();
            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                System.out.println("连接成功");
                // 请求返回的数据
                InputStream in1 = conn.getInputStream();
                try {
                    String readLine = new String();
                    BufferedReader responseReader = new BufferedReader(
                            new InputStreamReader(in1, "UTF-8"));
                    while ((readLine = responseReader.readLine()) != null) {
                        sb.append(readLine).append("\n");
                    }
                    responseReader.close();
                } catch (Exception e1) {
                    return "发送微信通知请求出现异常！" + e1.getMessage();
                }
            } else {
                logger.error("http connect  fail");
            }
        } catch (Exception e) {
            return "发送微信通知请求出现异常！" + e.getMessage();
        }
        return sb.toString();

    }

    public static String getRCCode(String url){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("Cookie", "JSESSIONID=DB3B1649E18D7DD1BEF36AFA5CF8684F; imgStatus=1")
                .build();
        try{
        Response response = client.newCall(request).execute();
        return JSONObject.fromObject(response.body().string().toString()).getString("object");
        }catch (Exception e){
            logger.error("人才code调用失败。");
            return null;
        }
    }

    public static String checkUser(String url,String token){
        try{
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .method("GET", null)
                    .addHeader("Authorization", token)
                    .addHeader("Cookie", "ns_remember_tokens=Int9Ig%3D%3D--cc18edc7a38b0a4b0313262118b3dcae3d2b0534")
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string().toString();
        }catch (Exception e){
            logger.error("获取第三方群众注册信息失败；url:"+url);
            return null;
        }
    }

    public static String getUser(String param,String url,String token){
        try{
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, param);
            Request request = new Request.Builder()
                    .url(url)
                    .method("POST", body)
                    .addHeader("Authorization", token)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("Cookie", "ns_remember_tokens=Int9Ig%3D%3D--cc18edc7a38b0a4b0313262118b3dcae3d2b0534")
                    .build();
            Response response = client.newCall(request).execute();
            return response.body().string().toString();
        }catch (Exception e){
            logger.error("注册第三方信息失败；url:"+url);
            return null;
        }
    }

    public static String sendQueue(String url,String result) {
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String entityStr = null;
        CloseableHttpResponse response = null;
        try {
            // 创建POST请求对象
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type",
                    "application/x-www-form-urlencoded; charset=UTF-8");
            httpPost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpPost
                    .addHeader("User-Agent",
                            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            httpPost.setEntity(new StringEntity(result,"utf-8"));
            httpPost.setHeader("Content-type", "application/json");
            // 执行请求
            response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e) {
            System.err.println("Http协议出现问题");
            e.printStackTrace();
        } catch (ParseException e) {
            System.err.println("解析错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO异常");
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    System.err.println("释放连接出错");
                    e.printStackTrace();
                }
            }
        }
        // 打印响应内容
        return entityStr;
    }

    public static String toHttpStreet(String url){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .build();
        try{
            Response response = client.newCall(request).execute();
            return response.body().string().toString();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("get street is error ："+e.getMessage());
            logger.error("url:"+url);
        }
        return null;

    }

    public static String sendPostTell(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("method", "post");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset:UTF-8");
            //conn.setRequestProperty("Content-type", "application/json; charset=utf-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
          /*  // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            */
            conn.getOutputStream().write(param.getBytes("GBK"));
            // flush输出流的缓冲
            //out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"GBK"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            return "操作失败："+e.getMessage();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                return "操作失败："+ex.getMessage();
            }
        }
        return result;
    }

    public static String getStreetValue(String url,String authorization){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("Authorization", authorization)
                .build();
        try{
            Response response = client.newCall(request).execute();
            return response.body().string().toString();
        }catch (Exception e){}
       return null;
    }

    public static String shinei(String url,String fid,String wcode){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\r\n  \"appid\": \"wxa1ebd30b775eda4e\",\r\n  \"fid\": \""+fid+"\",\r\n  \"jcode\": \"wxa0001\",\r\n  \"sid\": \"86010005050001\",\r\n  \"wcode\": \""+wcode+"\"\r\n}");
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        try{
            Response response = client.newCall(request).execute();
            return response.body().string().toString();
        }catch (Exception e){}
        return null;
    }

    public static String getSNUrl(String url){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\r\n\"appid\": \"wxa1ebd30b775eda4e\",\r\n\"fid\": \"F1\",\r\n\"jcode\": \"homepage\",\r\n\"sid\": \"86010005050001\"\r\n}");
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        try{
            Response response = client.newCall(request).execute();
            return JSONObject.fromObject(response.body().string().toString()).getString("data");
        }catch (Exception e){}
        return null;
    }

    public static void delGXTask(String ids,String reason,String userid,String url){
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("ids",ids)
                .addFormDataPart("reason",reason)
                .addFormDataPart("userid",userid)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("DELETE", body)
                .build();
        try{
            Response response = client.newCall(request).execute();
        }catch (Exception e){
            logger.error("街道表单撤销："+e.getMessage());
        }
    }
}
